import jwt from "jsonwebtoken";

export const COOKIE_KEY = "yun_jwt";

const generateTokenAndSetCookie = (userId, res) => {
  // openssl rand -base64 32
  const token = jwt.sign({ userId }, process.env.JWT_SECRET, {
    expiresIn: "15d", // 15天过期
  });
  res.cookie(COOKIE_KEY, token, {
    maxAge: 15 * 24 * 60 * 60 * 1000, // MS
    httpOnly: true, // prevent XSS sttacks cross-site scripting attacks
    sameSite: "strict", // CSRF attacks cross-site request forgery attacks
    secure: process.env.NODE_ENV !== "development", // cookie only works in https
  });
};

export default generateTokenAndSetCookie;
